package models

import (
	_ "github.com/lib/pq"
	"smallstory/datasource"
	"fmt"
	"database/sql"
	"time"
)

type User struct {
	Uid        string `json:"uid"`
	Name       string `json:"name"`
	HeaderImg  string `json:"img"`
	Createdate int64  `json:"createdate"`
}

type UserDao struct {
}

func (dao *UserDao) FindAll() {

}

func (dao *UserDao) Save(user *User) bool {

	connectInfo := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
		datasource.Host, datasource.Port, datasource.UserName, datasource.Password, datasource.DBname)
	db, err := sql.Open("postgres", connectInfo)
	if err != nil {
		panic(err)
	}
	defer db.Close()

	sqlStatement := `INSERT INTO t_user (uid, name, head,createdate)  VALUES ($1, $2, $3,$4)
					 ON CONFLICT(uid) DO UPDATE SET uid = $1, name =$2,head=$3,createdate=$4`
	result, err := db.Exec(sqlStatement, user.Uid, user.Name, user.HeaderImg, time.Now().UnixNano()/1e6)

	if err != nil {
		panic(err)
	}

	count, _ := result.RowsAffected()

	return count > 0
}
